import { AnimationAction, AnimationClip, AnimationMixer, Box3, Clock, Group, LoopOnce, Object3DEventMap, Vector3 } from "three";
import { ThreeLoader } from "../three/loader";
import { TextSprite } from "../sprite/text";
import { GLTF } from "three/examples/jsm/Addons.js";

export class RobotGltf {
    private threeLoader = new ThreeLoader();
    private textSprite = new TextSprite();
    private actions: { [key: string]: AnimationAction } = {};
    private clock = new Clock();
    private mixer!: AnimationMixer;

    loader(): Promise<GLTF> {
        return new Promise(resolve => {
            this.threeLoader.gltf().load('./assets/models/RobotExpressive.glb', object => {
                this.createAction(object)

                const robotObj = object.scene;
                robotObj.scale.set(0.5, 0.5, 0.5);

                // 主人物名字
                let spriteText = this.textSprite.canvas("robot");
                spriteText.position.set(0, 1.95, 0);
                robotObj.add(spriteText);

                const bbox = new Box3().setFromObject(robotObj);

                // 获取包围盒的中心点
                const center = new Vector3(0, 100, 0);
                bbox.getCenter(center);

                // 将物体移动到中心点
                robotObj.position.sub(center);

                resolve(object)
            })
        })
    }

    createAction(object: GLTF) {
        this.mixer = new AnimationMixer(object.scene);
        const animations = object.animations;


        for (let i = 0; i < animations.length; i++) {

            const clip = animations[i];
            const action = this.mixer.clipAction(clip);
            this.actions[clip.name] = action;
        }
    }

    fadeToAction(name: string, duration = 0.2) {
        const activeAction = this.actions[name];

        activeAction
            .reset()
            .setEffectiveTimeScale(1)
            .setEffectiveWeight(1)
            .fadeIn(duration)
            .play();

    }

    animate() {
        const dt = this.clock.getDelta();
        if (this.mixer) this.mixer.update(dt);
    }


}

